﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Reflection;
using System.Linq;

namespace GoodStuff.Silverlight
{
    /// <remarks>
    /// Courtesy of Rob Eisenberg
    /// http://live.visitmix.com/MIX10/Sessions/EX15
    /// </remarks>    
    public class ViewLocator
    {
        /// <summary>
        /// Locates the View that relates to the given ViewModel
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        public static FrameworkElement Locate(ViewModelBase viewModel)
        {
            Type t = viewModel.GetType();
            if (t.IsDefined(typeof(OverrideViewAttribute), false))
            {
                OverrideViewAttribute attribute = (OverrideViewAttribute)t.GetCustomAttributes(typeof(OverrideViewAttribute), false).FirstOrDefault();

                var view = (FrameworkElement)Activator.CreateInstance(attribute.View);
                return view;
            }
            else
            {
                Assembly ass = t.Assembly;
                var viewModelName = t.FullName;
                if (t.IsGenericType)
                {
                    viewModelName = t.GetGenericTypeDefinition().FullName;
                    viewModelName = viewModelName.Replace("`1", "");
                }
                var viewName = viewModelName.Replace("ViewModel", "View");
                var viewType = ass.GetType(viewName);
                if (viewType == null)
                {
                    throw new Exception("Unable to locate view class '" + viewName + "'for ViewModel '" + viewModelName + "'");
                }

                var view = (FrameworkElement)Activator.CreateInstance(viewType);
                return view;
            }
        }
    }
}
